package com.fanghaoran.dao;

import com.fanghaoran.bean.Interaction;
import com.fanghaoran.entity.Words;
import com.fanghaoran.view.user.bookFrame.BookCoverPanel;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: win11
 * @Date: 2023/03/22/13:09
 * @Description: 单词部分的数据库操作
 */
public class WordDao {

    /**
     * 获取单词数据
     */
    public Interaction getData() throws Exception {
        //先调用BaseDao方法,把数据库中的单词数据存到一个集合中
        String sql=null;
        //判断需要哪本书的单词数据
        if(BookCoverPanel.bookID==BookCoverPanel.CET4){
            sql="select word.id,word.word,word.translation " +
                    "from word_book " +
                    "join word on word_book.word_id=word.id " +
                    "where word_book.book_id=1;";
        }else if(BookCoverPanel.bookID==BookCoverPanel.CET6){
            sql="select word.id,word.word,word.translation " +
                    "from word_book " +
                    "join word on word_book.word_id=word.id " +
                    "where word_book.book_id=2;";
        }
        //返回单词数据
        List<Words> words = BaseDao.executeQuery(Words.class, sql);
        return new Interaction(null,words);
    }

    /**
     * 更新生词本
     */
    public void updateNotedBook(Words word,int userId) throws Exception {
        //先查询生词本是否已有这个单词
        @SuppressWarnings("unchecked")
        List<Words> wordsList=(List<Words>)getDataOfNoteBook(userId).getMessage();
        int flag=0;
        for (Words words : wordsList) {
            if(words.getWord().equals(word.getWord())){
                flag=1;
                break;
            }
        }
        //没有才会执行数据库存入操作
        if(flag==0) {
            String sql = "insert into note_word(userId,word,translation) values(?,?,?);";
            BaseDao.executeUpdate(sql, userId, word.getWord(), word.getTranslation());
        }
    }
    /**
     * 获取生词本数据
     */
    public Interaction getDataOfNoteBook(int userId) throws Exception {
        String sql="select word,translation from note_word " +
                "join user_info on user_info.id=note_word.userId " +
                "where userId=?;";
        List<Words> wordsList = BaseDao.executeQuery(Words.class, sql, userId);
        return new Interaction(null,wordsList);
    }
}
